package com.ss.zsensm;

import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.GradientDrawable;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ZSButtonWidget extends ZSWidget {
	private TextView btn;
	private Rect region;
	int[] origin;
	
	static GradientDrawable btnDownDrawable = new GradientDrawable(), 
			btnUpDrawable = new GradientDrawable();
	static {
		btnDownDrawable.setColor(Color.BLACK);
		btnDownDrawable.setStroke(10, Color.GRAY);
		btnDownDrawable.setCornerRadius(30.f);
		
		btnUpDrawable.setColor(Color.WHITE);
		btnUpDrawable.setStroke(10, Color.CYAN);
		btnUpDrawable.setCornerRadius(30.f);
	}
	
	public ZSButtonWidget(MainActivity mainActivity, String text, Rect pos) {
		super(mainActivity);
		btn = new Button(mainActivity);
		btn.setText(text);
		origin = new int[2];
		region = pos;
	}
	
	public int register(int id) {
		idx = id;
		btn.setId(this.mainActivity.getGlobalId());
		btn.setClickable(false);
		return id + 1;
	}
	
	public void install() {
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
				(int)(((float) region.width() / 100) * this.mainActivity.getLayoutWidth()), 
				(int)(((float) region.height() / 100) * this.mainActivity.getLayoutHeight()));
		
		lp.leftMargin = (int)(((float) region.left / 100) * this.mainActivity.getLayoutWidth());
		lp.topMargin = (int)(((float) region.top / 100) * this.mainActivity.getLayoutHeight());
		
		this.mainActivity.getLayout().addView(btn, lp);
		
	    btn.setBackgroundDrawable(btnUpDrawable);
		btn.setTextColor(Color.BLACK);
	}
	
	public boolean onPointerUp(int buttonId) {
		if (buttonId == btn.getId()) {
		    btn.setBackgroundDrawable(btnUpDrawable);
			btn.setTextColor(Color.BLACK);
			mainActivity.OnDataChange(idx, (byte) 0);
			return true;
		}
		return false;
	}
	
	public int onPointerDown(int x, int y) {
		btn.getLocationOnScreen(origin);
		region.set(origin[0], origin[1], origin[0] + btn.getWidth(), origin[1] + btn.getHeight());
		if (region.contains(x, y)) {
		    btn.setBackgroundDrawable(btnDownDrawable);
			btn.setTextColor(Color.WHITE);
			mainActivity.OnDataChange(idx, (byte) 1);
			return btn.getId();
		}
		return -1;
	}

	@Override
	public void uninstall() {
		this.mainActivity.getLayout().removeView(btn);
	}
}
